<?php
/**
 * 江远
 * 2018/11/28
 * 用户管理控制类
 */
namespace app\tdmin\controller;

use think\Db;
use think\Request;

class Authuser extends Common
{
    /**
     * 用户列表
     * @author 雨夜
     * @DateTime 2019-3-18 13:54:51
     */
    public function index(Request $request)
    {
        if($request->isAjax()){
            $uids = db('auth_group_access')->where([['group_id','neq',2]])->column('uid');
            $map[] = ['id','in',$uids];
            $userList = model('AuthUser')->where($map)->page(input('page'), input('limit'))->order('create_time desc')->select();
            foreach ($userList as $k => $v) {
                $userList[$k]['lastlogintime'] = $v['lastlogintime'] ? date('Y-m-d H:i', $v['lastlogintime']) : '';
            }
            $result['data']  = $userList;
            $result['count'] = model('AuthUser')->count();
            $result          = array_merge($this->api_code[0], $result);
            return json($result);
        }
        $role = db('AuthGroup')->where(['status'=>1])->select();
        $this->assign('roles',$role);
        return $this->fetch();
    }

    /***
     * 添加用户
     */
    public function addAuthUser()
    {
        if($this->request->isAjax()){
            $rule = [
                'nickname|昵称'   => 'require',
                'realname|真实姓名' => 'require',
                'account|账号'    => 'require|alphaNum',
                'mobile|手机号'    => 'require|mobile',
                'frozen|状态'     => 'require|in:0,1',
                'avatar|头像'     => 'require',
                'group_id|角色'   => 'require|array',
                'password'      => 'require',
            ];
            $post     = input();
            $validate = $this->validate($post, $rule);
            if (true !== $validate) {
                return json(['code' => 44001, 'msg' => $validate]);
            }
            $post['password'] = md5(md5($post['password']));
            $User             = model('AuthUser');
            $r                = $User->isUpdate(false)->allowField(true)->save($post);
            if (false !== $r) {
                $uid = $User->id;
                foreach ($post['group_id'] as $v) {
                    db('auth_group_access')->insert(['uid' => $uid, 'group_id' => $v]);
                }
                $this->api_code[0]['msg'] = '添加用户成功';
                return json($this->api_code[0]);
            } else {
                $this->api_code[40001]['msg'] = '添加用户失败';
                return json($this->api_code[40001]);
            }
        }
        return $this->fetch();
    }

    /***
     * 编辑用户
     * @author 雨夜
     */
    public function editAuthUser()
    {
        if($this->request->isAjax()){
            $rule = [
                'nickname|昵称'   => 'require',
                'realname|真实姓名' => 'require',
                'account|账号'=>'require|alphaNum',
                'mobile|手机号'    => 'require|mobile',
                'frozen|状态'     => 'require|in:0,1',
                'avatar|头像'     => 'require',
                'group_id|角色'   => 'require|array',
                'id|用户ID'       => 'require|number',
            ];
            $post     = input();
            // $validate = $this->validate($post, $rule);
            // if (true !== $validate) {
            //     return json(['code' => 44001, 'msg' => $validate]);
            // }
            if (isset($post['password'])) {
                $post['password'] = md5(md5($post['password']));
            } else {
                unset($post['password']);
            }
            $User = model('AuthUser');
            $r    = $User->isUpdate(true)->allowField(true)->save($post);
            if (false !== $r) {
                if(isset($post['group_id'])){
                    db('auth_group_access')->where(['uid' => $post['id']])->delete();
                    foreach ($post['group_id'] as $v) {
                        db('auth_group_access')->insert(['uid' => $post['id'], 'group_id' => $v]);
                    }
                }
                $this->api_code[0]['msg'] = '编辑用户成功！';
                return json($this->api_code[0]);
            } else {
                $this->api_code[40001]['msg'] = '编辑用户失败！';
                return json($this->api_code[40001]);
            }
        }else{
            $uid  = input('uid');
            $info = model('AuthUser')->field('uid,nickname,realname,usertype,mobile,frozen,avatar,level')->where('uid', 'eq', $uid)->find();
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    /***
     * 删除用户
     * @author 江远
     */
    public function delAuthUser()
    {
        $uid     = input('uid');
        $where[] = array('uid', 'eq', $uid);
        $r       = Db::name('AuthUser')->where($where)->delete();
        if ($r) {
            $this->api_code[0]['msg'] = '删除用户成功！';
            return json($this->api_code[0]);
        } else {
            $this->api_code[40001]['msg'] = '删除用户失败！';
            return json($this->api_code[40001]);
        }
    }

    /***
     * 根据ID获取用户的信息
     * @author 江远
     */
    public function getUserInfoById()
    {
        $uid = input('uid');
        if (empty($uid)) {
            $this->api_code[40001]['msg'] = '参数不正确！';
            return json($this->api_code[40001]);
        }
        $where[]        = array('id', 'eq', $uid);
        $info           = model('AuthUser')->where($where)->find();
        $info['groups'] = db('auth_group_access')->where(['uid' => $uid])->column('group_id');

        if ($info) {
            $this->api_code[0]['msg']  = '获取用户信息成功！';
            $this->api_code[0]['data'] = $info;
            return json($this->api_code[0]);
        } else {
            $this->api_code[40001]['msg'] = '获取用户信息失败！';
            return json($this->api_code[40001]);
        }
    }
    /**
     * 我的个人信息
     * @author 秋水
     * @DateTime 2019-02-12T16:04:18+0800
     */
    public function myProfile()
    {
        if(request()->isPost()) {
            $uid = session('admin_uid');
            $id = input('id', 0);
            $nickname = input('nickname', '');
            $mobile = input('mobile', '');
            $frozen = input('frozen', '');
            $avatar = input('avatar', '');

            if($uid != $id) {
                return json(['code'=>40001,'msg'=>'用户信息错误']);
            }

            $updateData = [
                'nickname' => $nickname,
                'mobile' => $mobile,
                'frozen' => $frozen,
                'avatar' => $avatar
            ];

            $r = model('AuthUser')->where([['id','eq',$id]])->update($updateData);
            if($r !== false) {
                return json(['code'=>0,'msg'=>'修改成功']);
            } else {
                return json(['code'=>40001,'msg'=>'修改失败']);
            }
        } else {
            $uid = session('admin_uid');
            $user = model('AuthUser')->where([['id','eq',$uid]])->find();

            $this->assign('data',$user);
            return $this->fetch();
        }
    }

    /**
     * 重置密码
     * @author 秋水
     * @DateTime 2019-02-12T16:22:26+0800
     */
    public function resetPassword()
    {
        if(request()->isPost()) {
            $uid = session('admin_uid');
            $id = input('id', 0);
            $opassword = input('opassword', '');
            $rpassword = input('rpassword', '');
            $password = input('password', '');

            if($uid != $id) {
                return json(['code'=>40001,'msg'=>'用户信息错误']);
            }

            if($password !== $rpassword) {
                return json(['code'=>40001,'msg'=>'两次输入不一致']);
            }

            $user = model('AuthUser')->where([['id','eq',$id]])->find();
            if(md5(md5($opassword)) != $user['password']) {
                return json(['code'=>40001,'msg'=>'原始密码不正确']);
            }

            $updateData = [
                'password' => md5(md5($password))
            ];

            $r = model('AuthUser')->where([['id','eq',$id]])->update($updateData);
            if($r !== false) {
                return json(['code'=>0,'msg'=>'修改成功']);
            } else {
                return json(['code'=>40001,'msg'=>'修改失败']);
            }
        } else {
            $uid = session('admin_uid');

            $this->assign('id',$uid);
            return $this->fetch();
        }
    }
}
